package zuoye.zy3;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
    private static final Pattern OP_PATTERN = Pattern.compile("[+\\-*/]");

    public static void main(String[] args) throws IOException {
        File dest  = new File("D:\\javabase_ws\\javaAdvanceProject\\untitled\\src\\zuoye\\zy3\\results.txt");
        File src = new File("D:\\javabase_ws\\javaAdvanceProject\\untitled\\src\\zuoye\\zy3\\questions.txt");

        List<String> lines = FileUtils.readLines(src, StandardCharsets.UTF_8);
        StringBuilder sb   = new StringBuilder();   // 收集所有结果

        for (String line : lines) {
            // 1. 找运算符
            Matcher m = OP_PATTERN.matcher(line);
            if (!m.find()) {
                sb.append(line).append(" = 格式错误\r\n");
                continue;
            }
            char op = m.group().charAt(0);
            System.out.println("运算符：" + op);

            // 2. 分割 & 转数字
            String[] parts = line.split("[+\\-*/]");
            int num1 = Integer.parseInt(parts[0].trim());
            int num2 = Integer.parseInt(parts[1].trim());

            // 3. 计算
            int result;
            switch (op) {
                case '+': result = num1 + num2; break;
                case '-': result = num1 - num2; break;
                case '*': result = num1 * num2; break;
                case '/': result = num1 / num2; break;
                default : result = 0;
            }

            // 4. 记录结果
            sb.append(line).append(" = ").append(result).append("\r\n");
        }

        // 5. 一次性覆盖写入
        FileUtils.writeStringToFile(dest, sb.toString(), StandardCharsets.UTF_8);
        System.out.println("计算完成，结果已写入 results.txt");
    }
}